# -*- coding: utf-8 -*-
from db.mysql import MysqlClient
import json
from common.config import *
from common.helper import Helper
from itertools import product
import requests


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "国华海陆空全球保"

    def genProductInfo(self):
        plan = {
            "planA": {
                "days": ["1d", "7d", "15d", "30d", "180d", "365d"],
                "people_count": ["1"],
                "airplane_death": ["2000000"],
                "private_death": ["200000"],
                "train_death": ["300000"],
                "ship_death": ["300000"],
                "bus_death": ["300000"],
                "accident_death": ["1000"]
            },
            "planB": {
                "days": ["1d", "7d", "15d", "30d", "180d", "365d"],
                "people_count": ["1"],
                "airplane_death": ["4000000"],
                "private_death": ["400000"],
                "train_death": ["600000"],
                "ship_death": ["600000"],
                "bus_death": ["600000"],
                "accident_death": ["2000"]
            },
            "planC": {
                "days": ["1d", "7d", "15d", "30d", "180d", "365d"],
                "people_count": ["1"],
                "airplane_death": ["6000000"],
                "private_death": ["600000"],
                "train_death": ["900000"],
                "ship_death": ["900000"],
                "bus_death": ["900000"],
                "accident_death": ["3000"]
            }

        }
        for k in plan:
            for v in product(plan[k]["days"], plan[k]["people_count"], plan[k]["airplane_death"],
                             plan[k]["private_death"], plan[k]["train_death"], plan[k]["ship_death"],
                             plan[k]["bus_death"], plan[k]["accident_death"]):
                data = Helper.formatProductInfo(plan[k], v)
                yield data

    # 执行爬虫
    def requestJson(self):
        for v in self.genProductInfo():
            if v["airplane_death"] == "2000000":
                plan = "基础计划"
            elif v["airplane_death"] == "4000000":
                plan = "标准计划"
            else:
                plan = "尊享计划"
            data = {"productCode": "691", "productName": plan, "salePlanCode": "GHGW_1008", "sex": "0",
                    "birthDate": "1978-11-05", "insurePeriod": v["days"].upper(), "type": "web", "system": "gh"}
            payload = json.dumps( data )
            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

            if r.status_code == 200 and "成功" in r.text :
                price = r.json()["content"]["resultPrice"]
                data = {
                    "name":self.name,
                    "company":"国华人寿",
                    "price":price
                }
                data.update( v )
                Helper.mergeTable(self.name,self.mysql,data )
